package com.axungu.web.freemarker.components;

import com.axungu.common.ServletContext;
import com.axungu.common.paginator.domain.Paginator;
import com.axungu.web.freemarker.FreemarkerComponent;
import freemarker.ext.beans.StringModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author jtoms.shen
 * @version 1.0
 * @date 2018/12/12 11:00
 */
@Slf4j
@FreemarkerComponent("showPaginator")
public class ShowPaginatorMethod implements TemplateMethodModelEx {
    @Override
    public Object exec(List list) throws TemplateModelException {

        StringModel stringModel = (StringModel) list.get(0);
        Paginator paginator = (Paginator) stringModel.getAdaptedObject(Paginator.class);

        String pageParamName = "page";
        if (list.size() > 1 && list.get(1) != null) {
            pageParamName = list.get(1).toString();
        }

        Map<String, String> dataMap = ServletContext.getRequestParamMap();

        HttpServletRequest request = ServletContext.getRequest();
        String url = request.getRequestURI() + "?";

        if (!dataMap.isEmpty()) {
            StringBuilder queryString = new StringBuilder();
            for (String key : dataMap.keySet()) {
                if (StringUtils.equals(pageParamName, key)) {
                    continue;
                }
                queryString.append(key).append("=").append(dataMap.get(key)).append("&");
            }
            url += queryString;
        }

        StringBuilder sb = new StringBuilder("<div id='paginator'></div>");
        sb.append("<script>");
        sb.append("layui.use(['laypage'], function () {");
        sb.append("var laypage = layui.laypage;");
        sb.append("laypage.render({");
        sb.append("elem: 'paginator',");
        sb.append("limit:").append(paginator.getLimit()).append(",");
        sb.append("curr: ").append(paginator.getPage()).append(",");
        sb.append("layout: ['count', 'prev', 'page', 'next', 'limit'],");
        sb.append("count: ").append(paginator.getTotalCount()).append(",");
        sb.append("jump: function (obj) {");
        sb.append("if(obj.curr !== ").append(paginator.getPage()).append("){");
        sb.append(" window.location.href = '").append(url).append("'+ 'page=' + obj.curr;");
        sb.append(" }");
        sb.append(" }})});");
        sb.append("</script>");

        return sb.toString();
    }
}
